import matplotlib.pyplot as plt
from sklearn import neighbors
from sklearn.datasets.samples_generator import make_blobs
from sklearn.cluster import AffinityPropagation
import scipy.io as scio
from sklearn.decomposition import PCA
from numpy import unique
from numpy import where
import random
import itertools

import numpy as np
import h5py as h5
import pandas as pd
from multiprocessing import Queue
import multiprocessing
from heapq import *
import math
from tqdm import tqdm
def accuracy(prediction, labels):
    return np.mean(np.sqrt(np.sum((prediction - labels) ** 2, 1)))
def knn_reg(off_rss,off_loc,trace,rss,k):
    # uniform 本节点所有邻节点投票权重一样
    # weight 投票权重
    knn_reg = neighbors.KNeighborsRegressor(k, weights='uniform', metric='euclidean')
    # print(knn_reg)
    knn_reg.fit(off_rss, off_loc)
    predictions = knn_reg.predict(rss)
    print(predictions - trace)
    # plt_loc_rea(predictions,trace,name='预测后的点与真实点对比'+str(k))
    acc = accuracy(predictions, trace)
    print("acc:", acc , "m")
    # for i in range(len(predictions)):
    #     print(predictions[i],trace[i])
    return acc / 100

if __name__ == '__main__':
    # 离线数据
    path16 = 'D:/Python workspace/chan/channels_July16.mat'
    data16 = h5.File(path16, 'r')
    off_rss = data16['RSSI'][:]
    off_xy = data16['labels'][:]
    off_xy = off_xy.T
    off_rss = off_rss.T
    off_xy = off_xy[::100]
    off_rss = off_rss[::100]
    off_xy = off_xy.T
    off_rss = off_rss.T

    print(off_rss.shape)
    print(off_xy.shape)

    # 在线数据
    path18 = 'D:/Python workspace/chan/channels_July18.mat'

    data18 = h5.File(path18, 'r')
    # print(data18['RSSI'][1:2][0:100])
    on_rss = data18['RSSI'][:]
    on_xy = data18['labels'][:]
    da_on_rss = pd.DataFrame(on_rss)
    da_on_xy = pd.DataFrame(on_xy.T)
    da_on_rss.to_csv('da_on_rss.csv')
    da_on_xy.to_csv('da_on_xy.csv')
    # on_rss = on_rss[::50]
    # on_xy = on_xy[::50]

    # # 离线轨迹
    plt.scatter(off_xy[0][:], off_xy[1][:])
    plt.show()
    # 在线轨迹
    plt.scatter(on_xy[0][:], on_xy[1][:])
    plt.show()

    off_rss = off_rss.T
    off_xy = off_xy.T
    # on_rss = on_rss.T
    on_xy = on_xy.T
    # # knn_reg(off_rss, off_xy, on_xy, on_rss, 5)
    #
    # df = pd.DataFrame(off_xy)
    #
    # print(off_xy.shape)
    #
    # # df.to_csv('off_xy.csv')
    #
    off_xy_idw = off_xy
    off_rss_idw = off_rss
    # print(off_xy)
    # print('shape',off_xy.shape)
    # print(off_rss.shape)
    # # data_off_rss = pd.DataFrame(off_rss)
    # # data_off_rss.to_csv('origin_rss.csv')
    n = 20
    num = 1000
    for i in tqdm(range(num)):  # 随机数个数
        a = round(random.uniform(-0.1, 8),3)
        b = round(random.uniform(-0.1, 5),3)
        if a not in off_xy[:]:
            off_xy_idw = np.append(off_xy_idw,[[a,b]],axis=0)
            d = np.array([[math.sqrt(math.pow(a - j[0],2) + math.pow(b - j[1],2)) for j in off_xy],[k for k in off_rss]],dtype=object)
            # print(d)
            data = pd.DataFrame(d.T)
            data.sort_values(by=0,axis=0,ascending=[True],inplace=True)
            data.reset_index(drop=True, inplace=True)
            # print('type(data)',type(data))
            # print(data)
            di = data.loc[0:n][0]
            rssi = data.loc[0:n][1]
            di_sum = (1 / di).sum()
            r_list = list()
            di_rss_sum1 = 0
            di_rss_sum2 = 0
            di_rss_sum3 = 0
            for m in range(rssi.shape[0]):
                di_rss_sum1 += rssi[m][0] * (1 / di[m])
                di_rss_sum2 += rssi[m][1] * (1 / di[m])
                di_rss_sum3 += rssi[m][2] * (1 / di[m])
            di_rss_sum1 /= n
            di_rss_sum2 /= n
            di_rss_sum3 /= n
            di_sum /= n
            r_list.append(di_rss_sum1 / di_sum)
            r_list.append(di_rss_sum2 / di_sum)
            r_list.append(di_rss_sum3 / di_sum)
            # print(r_list)
            off_rss_idw = np.append(off_rss_idw,[r_list],axis=0)

    print(off_rss_idw.shape)


    off_xy_idw = off_xy_idw.T
    off_xy = off_xy.T
    plt.figure(dpi=300)
    plt.scatter(off_xy[0:1,0:off_xy.shape[1]], off_xy[1:2,0:off_xy.shape[1]],color='blue',s=4)
    plt.scatter(off_xy_idw[0:1,off_xy.shape[1]:off_xy_idw.shape[1]], off_xy_idw[1:2,off_xy.shape[1]:off_xy_idw.shape[1]],color='red',s=4)
    plt.show()
    df = pd.DataFrame(off_xy_idw.T)
    df.to_csv(f'off_xy_idw{n}_num_{num}.csv')
    df = pd.DataFrame(off_rss_idw)
    df.to_csv(f'off_rss_idw{n}_num_{num}.csv')

